import { Tool } from '../../../Tool';

/**
 * 构件隔离
 */
export class ComponentIsolateTool extends Tool {
	constructor(viewer) {
		super(arguments);
		this.viewer = viewer;
		this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		this.selected = null;
		this.hidedLayers = [];
	}

	generateArray(start, end) {
		const array = [];
		for (let i = start; i <= end; i++) {
			array.push(i);
		}
		return array;
	}

	start() {
		this.handler.setInputAction((e) => {
			const clickObj = this.viewer.scene.pick(e.position);
			if (Cesium.defined(clickObj) && typeof clickObj.id === 'string') {
				const layer = clickObj.primitive;
				const name = layer.name;
				layer.datasetInfo().then((datasets) => {
					let layerIds = [];
					for (const dataset of datasets) {
						layerIds = layerIds.concat(this.generateArray(dataset.startID, dataset.endID));
					}
					this.selected = {
						name: name,
						ids: layerIds
					};
					layer.selectColorType = Cesium.SelectColorType.MIX;
					const selectedIndex = layerIds.indexOf(Number(clickObj.id));
					layerIds.splice(selectedIndex, 1);
					layer.setObjsColor(layerIds, Cesium.Color.WHITE.withAlpha(0));
					for (const item of this.viewer.scene.layers.layerQueue) {
						if (item.visible) {
							this.hidedLayers.push(item);
							if (item !== layer) {
								item.visible = false;
							}
						}
					}
				});
			}
		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	}

	cancel() {
		this.handler = this.handler && this.handler.destroy();
		for (const layer of this.hidedLayers) {
			if (layer.name !== this.selected.name) {
				layer.visible = true;
			} else {
				layer.removeObjsColor(this.selected.ids);
				layer.selectColorType = 2;
			}
		}
	}
}
ComponentIsolateTool.toolId = 'ComponentIsolateTool';
